package com.hdl.school.utils;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.PlanTask;
import com.hdl.school.bean.PlanTaskSource;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
;

/**
 * Created by yunjian on 16/10/9.
 */
public class TaskManager {


    private static TaskManager taskManager;

    private List<PlanTask> planTasks;
    private List<PlanTaskSource> todayTask = new ArrayList<>();
    //当前任务
    private PlanTask currentTask;

    private Context context;
    //缓存之前获取的任务数据
    private String oldRes = null;

    private static SharedPreferences sharedPreferences;


    private TaskManager() {
        planTasks = new ArrayList<PlanTask>();
    }


    public static TaskManager getInstance() {
        if (taskManager == null) {
            taskManager = new TaskManager();
        }
        return taskManager;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences("school_iot", 0);
    }

    /**
     * 加载音视频播放任务
     */
    public void reloadAllTask() {
        if(sharedPreferences==null){
            Log.e("MQTTService","未获取到sharedPreferences");
            sharedPreferences = context.getSharedPreferences("school_iot", 0);
        }
        //获取课室信息
        String roomInfo = sharedPreferences.getString("room_info", null);
        if (roomInfo == null) {
            Log.e("MQTTService","未获取到房间信息");
            return;
        }
        //获取服务器地址
        String serverConfig = sharedPreferences.getString("serverConfig", null);
        if (serverConfig == null) {
            Log.e("MQTTService","未获取到serverIP");
            return;
        }
        JSONObject roomObj = JSON.parseObject(roomInfo);

        String url = String.format("http://%s/publicapi/terminal/task/plan/list/load?room_id=%s&trans=true", serverConfig, roomObj.getIntValue("roomId"));
        x.http().get(new RequestParams(url), new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Log.e("MQTTService",result);
                if (result != null) {
                    if (result.equals(oldRes)) {
                        return;
                    }
                    sharedPreferences.edit().putString("tasklist", result).commit();
                    parseTask(result);
                    oldRes = result;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("MQTTServiceErr",ex.getMessage());
                String str = sharedPreferences.getString("tasklist", null);
                if (str != null && (!str.equals(oldRes))) {
                    parseTask(str);
                    oldRes = str;
                }

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    private void parseTask(String taskStr) {
        if (taskStr == null) {
            return;
        }
        List<PlanTask> overTesks = new ArrayList<PlanTask>();
        List<PlanTaskSource> planSources0 = HttpResponseUtil.checkResponse(taskStr, PlanTaskSource.class);
        todayTask.clear();
        String serverConfig = sharedPreferences.getString("serverConfig", null);
        if (serverConfig == null) {
            return;
        }
        if (planSources0 != null && planSources0.size() > 0) {
            List<PlanTask> tasks = new ArrayList<>();
            long now = TimeUtil.currentStap();
            for (PlanTaskSource planSource : planSources0) {
                String mediaPath = planSource.getMediaPath();
                if (planSource.getTaskType() == 2) {
                    mediaPath = "http://" + serverConfig+"/" + mediaPath;
                } else {
                    mediaPath = planSource.getLiveUrl();
                }
                if (TimeUtil.string2Date(planSource.getPlanStartDate() + " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime() > now || TimeUtil.string2Date(planSource.getPlanEndDate() + " 23:59:59", "yyyy-MM-dd HH:mm:ss").getTime() < now) {
                    continue;
                }
                todayTask.add(planSource);
                //检查任务是否在开始结束日期之间
                switch (planSource.getTaskType()) {
                    case 0:
                    case 1:
                        //直播
                        long start = TimeUtil.timeInToday(planSource.getPlayStartTime());
                        long end = TimeUtil.timeInToday(planSource.getPlayEndTime());
                        if (end >= now) {
                            //开始任务
                            PlanTask planTask0 = new PlanTask();
                            planTask0.setTaskName(planSource.getTaskName());
                            planTask0.setFileUrl(mediaPath);
                            planTask0.setDownloadStatus(0);
                            planTask0.setLoop(true);
                            planTask0.setTime(start);
                            planTask0.setStopOther(planSource.getStopOther());
                            planTask0.setTimes(0);
                            planTask0.setStatus(1);
                            planTask0.setType(1);
                            //结束任务
                            PlanTask planTask1 = new PlanTask();
                            planTask1.setTaskName(planSource.getTaskName());
                            planTask1.setFileUrl(mediaPath);
                            planTask1.setDownloadStatus(1);
                            planTask1.setLoop(false);
                            planTask1.setTime(end);
                            planTask1.setTimes(0);
                            planTask1.setStatus(2);
                            planTask1.setType(1);
                            if (start > now) {
                                //待播放任务
                                tasks.add(planTask0);
                                tasks.add(planTask1);
                            } else {
                                //任务正在进行中
                                overTesks.add(planTask0);
                                overTesks.add(planTask1);
                            }
                        }

                        break;
                    case 2:
                        //定时任务
                        long startTime = TimeUtil.timeInToday(planSource.getPlayStartTime());
                        long endtime = TimeUtil.timeInToday(planSource.getPlayEndTime());
                        if (endtime >= now) {
                            if (planSource.getPlayRule() == 0) {
                                if (planSource.getMediaType() == 1 || planSource.getMediaType() == 2) {
                                    String du = planSource.getDuration();
                                    if (du != null && du.length() > 0) {
                                        String[] dus = du.split("_");
                                        long duration = Integer.parseInt(dus[0]) * 3600000L + Integer.parseInt(dus[1]) * 60000L + Integer.parseInt(dus[1]) * 1000L;
                                        if (now - startTime >= duration) {
                                            continue;
                                        }
                                    }
                                }

                            }
                            //开始任务
                            PlanTask planTask = new PlanTask();
                            planTask.setFileUrl(mediaPath);
                            planTask.setTaskName(planSource.getTaskName());
                            planTask.setDownloadStatus(0);
                            planTask.setTime(startTime);
                            planTask.setStopOther(planSource.getStopOther());
                            planTask.setTimes(planSource.getPlayRule());
                            planTask.setLoop(planSource.getPlayRule() == 1);
                            planTask.setStatus(1);
                            planTask.setType(2);
                            //结束任务
                            PlanTask planTask1 = new PlanTask();
                            planTask1.setFileUrl(mediaPath);
                            planTask1.setDownloadStatus(2);
                            planTask1.setTaskName(planSource.getTaskName());
                            planTask1.setLoop(false);
                            planTask1.setTime(endtime);
                            planTask1.setStatus(2);
                            planTask1.setType(2);
                            if (startTime > now) {
                                tasks.add(planTask);
                                tasks.add(planTask1);
                            } else {
                                overTesks.add(planTask);
                                overTesks.add(planTask1);
                            }

                        }

                        break;
                }
            }

            if (overTesks.size() >= 1) {
                Collections.sort(overTesks, new FileTaskComparator());
                for (int j = overTesks.size() - 1; j >= 0; j--) {
                    if (overTesks.get(j).getStatus() == 1) {
                        for (int k = j + 1; k < overTesks.size(); k++) {
                            if (overTesks.get(j).getFileUrl().equals(overTesks.get(k).getFileUrl())) {
                                tasks.add(overTesks.get(j));
                                tasks.add(overTesks.get(k));
                                break;
                            }
                        }
                        break;
                    }
                }
            }


            synchronized (planTasks) {
                planTasks = tasks;
                if (planTasks.size() > 0) {
                    //有播放任务获取最近的播放任务
                    Collections.sort(planTasks, new FileTaskComparator());
                    currentTask = planTasks.get(0);
                } else {
                    //没有播放任务，设置明天重新解析任务
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(TimeUtil.currentStap());
                    int nowDay = calendar.get(Calendar.DATE);
                    calendar.set(Calendar.DATE, nowDay + 1);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 10);
                    currentTask = new PlanTask();
                    currentTask.setType(3);
                    currentTask.setStatus(1);
                    currentTask.setTime(calendar.getTimeInMillis());
                }
            }
            //    FTPManager.getInstance().startTasks(tasks);
        } else {
            synchronized (planTasks) {
                //没有播放任务，设置明天重新解析任务
                planTasks.clear();
                Calendar calendar = Calendar.getInstance();
                int nowDay = calendar.get(Calendar.DATE);
                calendar.set(Calendar.DATE, nowDay + 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 10);
                currentTask = new PlanTask();
                currentTask.setStatus(1);
                currentTask.setType(3);
                currentTask.setTime(calendar.getTimeInMillis());
            }

        }
        //停止当前播放
        Intent stopIntent=new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
        stopIntent.putExtra("action","stopall");
        context.sendBroadcast(stopIntent);
        //刷新播放列表
        if(todayTask.size()>1){
            Collections.sort(todayTask, new PlanSourceComparator());
        }
        Intent intent=new Intent(BroadcastAction.ACTION_TASKLIST);
        intent.putExtra("tasks",JSON.toJSONString(todayTask));
        context.sendBroadcast(intent);
        setAlarm(currentTask.getTime());
    }


    public  void startCurrentTask() {
        if (currentTask != null) {
            Intent bIntent=new Intent(BroadcastAction.ACTION_MEDIA_ENVENT);
            bIntent.putExtra("action","");
            bIntent.putExtra("tasks",JSON.toJSONString(todayTask));
            context.sendBroadcast(bIntent);
            switch (currentTask.getStatus()) {
                case 1:
                    switch (currentTask.getType()) {
                        case 1:
                             MediaUtils.playMedia(context, currentTask);
                            break;
                        case 2:
                               MediaUtils.playMediaCheckLocal(context, currentTask);
                            break;
                        case 3:
                            String str = sharedPreferences.getString("tasklist", null);
                            if (str != null) {
                                parseTask(str);
                                oldRes = str;
                            }
                            break;
                    }
                    break;
                case 2:
                      MediaUtils.stopMeida(context, currentTask);
                    break;
            }

            waitNextAlarm();
        }
    }


    public void waitNextAlarm() {
        synchronized (planTasks) {
            if (planTasks != null) {
                if (currentTask != null) {
                    //移除已过时任务
                    long now = TimeUtil.currentStap();
                    List<PlanTask> mTasks=new ArrayList<>();
                    for (int i = 0; i < planTasks.size(); i++) {
                        PlanTask pt=planTasks.get(i);
                        if (pt.getTime() >= now) {
                            mTasks.add(pt);
                        }
                    }
                    planTasks=mTasks;
                }
                if (planTasks.size() > 0) {
                    Collections.sort(planTasks, new FileTaskComparator());
                    currentTask = planTasks.get(0);

                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(TimeUtil.currentStap());
                    int nowDay = calendar.get(Calendar.DATE);
                    calendar.set(Calendar.DATE, nowDay + 1);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    currentTask = new PlanTask();
                    currentTask.setType(3);
                    currentTask.setTime(calendar.getTimeInMillis());
                }
                handler.sendEmptyMessage(0);
            }
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    setAlarm(currentTask.getTime());
                    break;
            }
        }
    };


    public void setAlarm(long time) {
        if (time > 0) {
            Intent intent = new Intent(BroadcastAction.ACTION_ALARM);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            //获取闹钟管理器
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
            //设置闹钟
            alarmManager.set(AlarmManager.RTC_WAKEUP, time - MyApplication.getAppContext().timeoffset, pendingIntent);
            Log.e("alarm", TimeUtil.long2String(time, "yyyy-MM-dd HH:mm:ss") + (currentTask.getStatus() == 1 ? "播放" : "停止") + currentTask.getFileUrl());
        }
    }

}
